import Axios from 'axios';
import Qs from 'qs'
import { Message } from 'element-ui';
import { getStore, setStore } from './storage';
import Util from '@/utils/util';
import router from '@/router';
import Global from '@/utils/global';

// 统一请求路径前缀
let base = Global.getBaseUrl();

const isTesting = process.env.NODE_ENV == 'development';

const toLogin = () => {
    console.log('login')
    Message.closeAll();
    Message.error('登录已失效');
    router.push({
        path: '/login',
    });

    sessionStorage.clear();
}

/**
 * 错误判断
 */
const errorHandle = (code, msg) => {
    switch (code) {
        case 2001:
            toLogin();
            break;
    }
}

// // 超时设定
Axios.default.timeout = 30000;

Axios.interceptors.request.use(config => {
    return config;
}, err => {
    Message.error('请求超时');
    return Promise.resolve(err);
});

// http response 拦截器
Axios.interceptors.response.use(response => {
    return response;
}, err => {
    // 返回状态码不为200时的错误处理
    Message.error(err.toString());
    return Promise.resolve(err);
});

export const getRequest = (url, params = {}, { postNoAuth, contentType } = {}) => {
    let accessToken = getStore('accessToken');
    let axiosHeaders = {};
    if (contentType) axiosHeaders['Content-Type'] = contentType;
    if (!postNoAuth) axiosHeaders.webToken = accessToken;

    return new Promise((resolve, reject) => {
        Axios({
            method: 'get',
            url: `${base}${url}`,
            params: Qs.stringify(requestParams),
            headers: axiosHeaders
        }).then(response => {
            if (response.status && response.status == 200) {
                var resData = Qs.parse(response.data);

                if (resData && resData.code == 1) {
                    resolve(resData)
                } else {
                    reject((resData.msg && resData) || { msg: resData || 'RESPONSE ERROR' })
                }
            } else {
                console.log('=== Get Then Error ======================', response)
                reject({ msg: 'RESPONSE ERROR' })
            }
        }).catch((error) => {
            console.log('=== Get Catch Error ======================', error)
            reject(error);
        });
    })
};

export const postRequest = (url, params = {}, { postNoAuth, contentType, isQs,hasHisToken,hisToken } = {}) => {
    let accessToken = getStore('accessToken');
    // isQs = isQs || false;

    /* post 请求头 */
    let axiosHeaders = {};
    if (contentType) axiosHeaders['Content-Type'] = contentType;
  // if (!postNoAuth) axiosHeaders.webToken = accessToken;
    axiosHeaders.webToken = accessToken;
    if(hasHisToken)axiosHeaders.HisToken = hisToken;

    /* 参数加密 */
    let requestParams = {};
    /* isTesting */
    if (true) {
        requestParams = params || {};
    } else {
        let encryptStr = '';
        for (let it in params) {
            encryptStr += `${it}=${params[it]}&`;
        }
        requestParams = {
            content: Util.encrypt(encryptStr.substr(0, encryptStr.length - 1)),
            isEncrypt: '1'
        };
    }


    // requestParams = isQs ? Qs.stringify(requestParams) : requestParams;

    return new Promise((resolve, reject) => {
        Axios({
            method: 'post',
            url: `${base}${url}`,
            data: requestParams,
            headers: axiosHeaders
        }).then(response => {
            if (response && response.status && response.status == 200) {
                let res_data = Qs.parse(response.data);

                if (response.data.data) {
                    res_data.data = res_data.data;
                    // try {
                    //     res_data.data = typeof response.data.data == 'string' ? JSON.parse(Util.decrypt(res_data.data)) : res_data.data;
                    // } catch (err) {
                    //     reject({
                    //         code: 0,
                    //         msg: `执行数据解密失败！当前返回data类型为 ${typeof response.data.data}`
                    //     });
                    // }
                }

                if (res_data && res_data.code == 1) {
                    resolve(res_data);
                } else {
                    res_data.code && errorHandle(res_data.code)
                    reject((res_data.msg && res_data) || { msg: res_data || 'RESPONSE ERROR' })
                }
            } else {
                console.log('=== Post Then Error ======================', response)
                reject({ msg: 'ERROR' })
            }
        }).catch(error => {
            console.log('=== Post Catch Error ======================', error)
            if (error && error.code) errorHandle(error.code)
            reject(error);
        })
    })
};

export const putRequest = (url, params) => {
    let accessToken = getStore("accessToken");
    return Axios({
        method: 'put',
        url: `${base}${url}`,
        data: params,
        transformRequest: [function(data) {
            let ret = '';
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
            }
            ret = ret.substring(0, ret.length - 1);
            return ret;
        }],
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'accessToken': accessToken
        }
    });
};

export const postBodyRequest = (url, params) => {
    let accessToken = getStore('accessToken');
    return Axios({
        method: 'post',
        url: `${base}${url}`,
        data: params,
        headers: {
            'accessToken': accessToken
        }
    });
};
